package com.wlyuan.open.scanner.repository.impl;

import com.wlyuan.open.scanner.dao.entity.BalanceBillindexDO;
import com.wlyuan.open.scanner.dao.mapper.BalanceBillindexMapper;
import com.wlyuan.open.scanner.domain.finance.Bill;
import com.wlyuan.open.scanner.domain.finance.BillConvert;
import com.wlyuan.open.scanner.domain.transport.Transport;
import com.wlyuan.open.scanner.repository.BillRepository;
import com.wlyuan.open.scanner.repository.FinanceBillRepository;
import com.wlyuan.open.utils.LongUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author lijing
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class PayBillCarrierCustomerRepository {
    private final BalanceBillindexMapper balanceBillindexMapper;
    private final FinanceBillRepository financeBillRepository;
    private final TenantCheckRepository tenantCheckRepository;
    private final BillRepository billRepository;


    public Bill getById(Long billId) {
        return Optional.ofNullable(billId).map(id -> {
            var finance = financeBillRepository.getByUpOrDown(id);
            return Optional.ofNullable(finance).map(data -> parse(data.getId(), data.getUp(), data.getDown(), data.getTenantId())).orElse(null);
        }).orElse(null);

    }

    public List<Transport> processWayBill(Long billId) {
        return billRepository.processWayBill(billId);
    }

    private Bill parse(Long id, Long up, Long down, Long tenantId) {
        if (tenantCheckRepository.checkTenant(tenantId)) {
            logger.error("对账单id：{},{},租户id:{}", up, down, tenantId);
            return null;
        }
        if (LongUtils.notNullLong(up) && LongUtils.notNullLong(down)) {
            var data = balanceBillindexMapper.getById(up);
            process(data, id);
            var bill = BillConvert.convert(data, down);
            bill.setUpStream(BillConvert.upConvert(data));
            //下游
            var downData = balanceBillindexMapper.getById(down);
            process(downData, id);
            bill.setDownStream(BillConvert.downConvert(downData));
            return bill;
        }
        //线下客户 up = null , down != null  / 线下承运方 up != null , down = null
        var data = LongUtils.notNullLong(up) ? balanceBillindexMapper.getById(up) : balanceBillindexMapper.getById(down);
        process(data, id);
        var bill = BillConvert.convert(data, down);
        bill.setDownStream(BillConvert.downConvert(data));
        bill.setUpStream(BillConvert.upConvert(data));
        return bill;
    }

    private void process(BalanceBillindexDO data, Long id) {
        //承运方信息
        billRepository.processCarrier(data);
        //发货方客户信息
        billRepository.processCustomer(data);
    }
}
